var express = require('express')
var winston = require('winston');
var schedule = require('node-schedule');
var moment = require('moment');
var engines = require('consolidate');

var logger = initExpressLogger();
logger.info("success components init started.");

var app = express();

initExpressGlobalConsts();
initExpressHtmlEngine();
initExpressActions();
initExpressBindingPort();
// scheduleJobs();

logger.info("success components init finished.");

function initExpressActions() {
	app.listen(8080);
	logger.info("success initExpressActions");
}
function initExpressBindingPort() {
	// mount static files.
	app.use('/open', express.static('/Users/Steve/tools/myGit/xNode/public'));

	app.get('/', function(req, res) {
		doGetAndPost(req, res);
	});

	app.post('/', function(req, res) {
		doGetAndPost(req, res);
	});
	logger.info("success initExpressBindingPort");
}

function initExpressLogger() {
	var logger = new (winston.Logger)(
			{
				transports : [ new (winston.transports.Console)(
						{
							timestamp : function() {
								return moment().format();
							},
							formatter : function(options) {
								// Return string will be passed to logger.
								return options.timestamp()
										+ ' '
										+ options.level.toUpperCase()
										+ ' '
										+ (undefined !== options.message ? options.message
												: '')
										+ (options.meta
												&& Object.keys(options.meta).length ? '\n\t'
												+ JSON.stringify(options.meta)
												: '');
							}
						}) ]
			});
	logger.info("success init global logger.");
	return logger;
}

function doGetAndPost(req, res) {
	// res.send('receive get or post here.' + req.query);
	res.render('one/test.html', {
		token : app.locals.home
	});
}

function initExpressHtmlEngine() {
	app.engine('html', engines.mustache);
	app.set('view engine', 'html');
	app.set('views', app.locals.home + '/views');
	logger.info("success initExpressHtmlEngine");
}

function initExpressGlobalConsts() {
	app.locals.email = "nevermissing@vip.qq.com";
	app.locals.home = __dirname;
	logger.info("success initExpressGlobalConsts");
}

function scheduleJobs() {
	logger.info("schedule job now.");
	var j = schedule.scheduleJob('/5 * * * * *', function() {
		logger.info("hellow world logging test here for str:%s", "test msg.");
	});
}